<?php

namespace GoWithCar\Controller;

use Common\Controller\ApiController;
use Common\Model\ModelException;
use Ruben\Yxyun\Yxim;
use Util\ModelUtils;

class GoWithCarController extends ApiController {

    protected $Model = NULL;
    protected $field = ['car_id', 'user_id', 'type', 'sex', 'who_show', 'start_time', 'hour', 'minute', 'num', 'end_position', 'start_position','end_poiname', 'start_poiname','is_ontime', 'mark', 'lng', 'lat', 'city', 'citycode', 'create_time', 'audit', 'delete_time', 'closed'];
    protected $user_field = ['user_id', 'face', 'nickname', 'sex', 'token'];

    public function _initialize() {
        parent::_initialize();
        $this->Model = D(CONTROLLER_NAME);
    }

    /*
     * 发布租房
     */

    public function store() {
        $input = $this->request();
        $this->checkNull($input, ['who_show', 'sex', 'type', 'start_time', 'num', 'end_position', 'start_position']);

        try {
            $id = $this->Model->publish($this->user['id'], $input);
            $this->createdResponse(['msg' => '发布成功', 'id' => $id, "url" => "/mobile/car/add"]);
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    /*
     * 更新租房
     */

    public function edit() {
        $input = $this->request();
        $this->checkNull($input, ['id', 'who_show', 'sex', 'start_position', 'end_position', 'num', 'start_time', 'type']);

        try {
            $this->Model->publish($this->user['id'], $input);
            $this->createdResponse(['msg' => '更新成功', "url" => "/mobile/car/add"]);
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
    }

    /*
     * 删除需求
     * 
     */

    public function del() {
        $user = $this->user;
        $input = $this->request();
        $id = $input['id'];
        $this->Model->where(['car_id' => $id, 'user_id' => $user['id'], 'delete_time' => 0])->setField('delete_time', time());
        $this->createdResponse(['msg' => '删除成功', "url" => ""]);
    }

    /*
     * 关闭和开启我的信息
     * 
     */

    public function closed() {
        $user = $this->user;
        $input = $this->request();
        $id = $input['id'];
        $closed = $input['closed'];
        $this->Model->where(['car_id' => $id, 'user_id' => $user['id'], 'delete_time' => 0])->setField('closed', $closed);
        $msg = $input['closed'] ? "关闭成功" : "开启成功";
        $this->createdResponse(['msg' => $msg, "url" => ""]);
    }

    /*
     * 收藏/取消收藏
     * 
     */

    public function favorite() {
        $user = $this->user;
        $input = $this->request();
        if ($user['id'] == $input['user_id']) {
            $this->errorResponse('401', '不能收藏自己的哦');
        }
        $RentroomFavoriteM = D('GoWithCarFavorite');
        $id = $input['id'];
        $del_id = $input['del_id'];
        $where['user_id'] = $user['id'];
        if ($del_id) {
            $RentroomFavoriteM->delete($del_id);
            $msg = "取消收藏成功";
            $this->createdResponse(['msg' => $msg, "url" => ""]);
        } else {
            $this->checkNull($input, ['id']);
            $id = $RentroomFavoriteM->add([
                'user_id' => $user['id'],
                'car_id' => $input['id'],
                'to_user_id' => $input['user_id'],
                'add_time' => time()
            ]);
            $msg = "添加收藏成功";
            $this->createdResponse(['msg' => $msg, 'favorite' => ['favorite_id' => $id, 'car_id' => $input['id']], "url" => ""]);
        }
    }

    /*
     * 
     * 我的历史需求
     */

    public function mytravel() {
        $user = $this->user;
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $where = $rentroom = $pagination = [];

        $where['user_id'] = $user['id'];
        $rentroomM = $this->Model;
        $count = $rentroomM->scope('history')->where($where)->count();

        if (!$count) {
            $this->response($rentroom, $pagination);
        }
        $rentroom = $rentroomM
                ->scope('history')
                ->where($where)
                ->order('create_time desc')
                ->page($page, $perPage)
                ->select();
        $pagination = pagination($count, $perPage, $page);
        $this->response($rentroom, $pagination);
    }

    /*
     * 
     * 我的收藏
     */

    public function myfavorite() {
        $user = $this->user;
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $where = $rentroom = $pagination = [];

        $where['user_id'] = $user['id'];
        $rentroomM = D('GoWithCarFavorite');
        $count = $rentroomM->where($where)->count();
        if ($count > 0) {
            $rentroom = $rentroomM
                    ->where($where)
                    ->order('add_time desc')
                    ->page($page, $perPage)
                    ->select();
            $rentroom = $this->getrelation3($rentroom);
            ModelUtils::belongsTo($rentroom, ['foreignKey' => 'to_user_id', 'relation' => 'Account/Users', 'fields' => $this->user_field, 'refKey' => 'user_id', 'name' => 'author']);
            ModelUtils::belongsTo($rentroom, ['foreignKey' => 'car_id', 'relation' => 'GoWithCar/GoWithCar', 'refKey' => 'car_id', 'fields' => $this->field, 'name' => 'travel']);
            foreach ($rentroom as $key => &$value) {
                if(empty($value['author'])){
                    array_splice($rentroom,$key,1);
                }
            }
        }

        $pagination = pagination($count, $perPage, $page);
        $this->response($rentroom, $pagination);
    }

    /*
     * 获取用户
     * 
     */

    public function search() {
        $input = $this->request();
        $page = (int) filter($input['page'], 1);
        $perPage = (int) filter($input['per_page'], 10);
        $uid = $this->user['id'];
        $where = $rentroom = $pagination = [];
        $where = $this->whoShow($input);
        if ($page == 1) {

            // 不修改前端前提下避免重复数据
            S('post_page_lock_' . $uid, time(), 60);
        } else {
            $lastest = S('post_page_lock_' . $uid);
            // 不能完全避免
            if ($lastest)
                $where['create_time'] = ['elt', $lastest];
        }
        if (!empty($input['sex'])) {
            $input['sex'] = $input['sex']==1?2:1;
            $where['sex'] = ['neq',$input['sex']];
        }

        if (!empty($input['start_time'])) {
            $start_time = $input['start_time'];
            $day = date("Y-m-d",$start_time);
            $time = $day.' '.intval($input['hour']).':'.intval($input['minute']);
            $where['start_time'] = ['egt', strtotime($time)];
        }

        $start_position = $input['start_position'];
        if (!empty($start_position)) {
            $where['start_position'] = ['like', "%{$start_position}%"];
        }
        $end_position = $input['end_position'];
        if (!empty($end_position)) {
            $where['end_position'] = ['like', "%{$end_position}%"];
        }
        $start_poiname = $input['start_poiname'];
        if (!empty($start_poiname)) {
            $where['start_poiname'] = ['like', "%{$start_poiname}%"];
        }
        $end_poiname = $input['end_poiname'];
        if (!empty($end_position)) {
            $where['end_poiname'] = ['like', "%{$end_poiname}%"];
        }
        $type = $input['type'];
        if (!empty($type)) {
            $where['type'] = $type;
        }

        $num = $input['num'];
        if (!empty($num)) {
            $where['num'] = $num;
        }
        $where['citycode'] = $input['citycode'];
        $where = array_filter($where);

        $order = [];
        $order['create_time'] = 'desc';
        $count = $this->Model->scope('valid')
//                ->cache('60')
                        ->where($where)->count();
        if ($count) {
            $rentroom = $this->Model
                    ->scope('valid')
//                ->cache('car','60')
                    ->where($where)
                    ->field($this->field)
                    ->order($order)
                    ->page($page, $perPage)
                    ->select();
            ModelUtils::belongsTo($rentroom, ['foreignKey' => 'user_id', 'relation' => 'Account/Users', 'refKey' => 'user_id', 'fields' => $this->user_field, 'name' => 'author']);
            ModelUtils::belongsTo($rentroom, ['foreignKey' => 'car_id', 'relation' => 'GoWithCar/GoWithCarFavorite', 'refKey' => 'car_id', 'where' => ['user_id' => $uid], 'name' => 'favorite']);
            $rentroom = $this->getrelation($rentroom);
            foreach ($rentroom as $key => &$value) {
                if(empty($value['author'])){
                    array_splice($rentroom,$key,1);
                }
            }
        }
        $pagination = pagination($count, $perPage, $page);
        $this->response($rentroom, $pagination);
    }

}
